package com.edu.dsai.service.impl;
import cn.dev33.satoken.stp.StpUtil;
//import com.edu.dsai.domain.History;
import com.edu.dsai.enums.SSEMsgType;
//import com.edu.dsai.mapper.HistoryMapper;
import com.edu.dsai.service.OllamaService;
import com.edu.dsai.utils.SSEServer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
@Service
@Slf4j
public class OllamaServiceImpl implements OllamaService {
    @Resource
    private OllamaChatClient ollamaChatClient;
//    @Resource
//    private HistoryMapper historyMapper;
    @Override
    public List<String> aiResponse(String userId, String msg) {
        Prompt prompt = new Prompt(new UserMessage(msg));
        Flux<ChatResponse> streamResponse = ollamaChatClient.stream(prompt);
        StringBuilder stringBuilder = new StringBuilder();
        List<String> list = streamResponse.toStream()
                .map(chatResponse -> {
                    String content = chatResponse.getResult()
                            .getOutput()
                            .getContent();
                    log.info(content);//后端在控制台输出给予的打字机回复信息
                    stringBuilder.append(content);
                    SSEServer.sendMessage(userId.toString(), content, SSEMsgType.ADD);
                    return content;
                })
                .toList();
        // 将生成的问答数据保存到数据库
//        History history = new History();
//        history.setMsg(msg);
//        history.setAnswer(stringBuilder.toString());
//        historyMapper.insert(history);
        return list;
    }
}